/* eslint-disable no-case-declarations */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Tab, Button, Balloon } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { Header, Content, YunxiaoIcon, YunxiaoTable, Title } from '@alife/devops-ui';
import { enterPage, Perf } from 'utils/track';
import FilterForm from './filterForm';
import { ENUM } from 'utils/constants.js';
import Qs from 'qs';
import * as actions from '../actions/index';
import dayjs from 'dayjs';
import SlsService from './slsService';
import docs from 'utils/docs';
import { getFeature } from 'utils/features';
import { navigateOpen } from 'utils/router';

// 加密级别： EncryptNewProject 新仓库默认加密， Default或空 选择开启
import intl from '../../../../../../../../../locale';

const cryptoLevelMap = {
  0: 'Default',
  1: 'EncryptNewProject',
};

const tabDataSource = [
  {
    value: intl.get({
      id: 'code-assets.audit.containers.root.DatabaseManagementLogs',
      defaultMessage: '库管理日志',
    }),

    key: 'project',
  },

  {
    value: intl.get({
      id: 'code-assets.audit.containers.root.CodeBehaviorLogs',
      defaultMessage: '代码行为日志',
    }),

    key: 'repo',
  },

  {
    value: intl.get({
      id: 'code-assets.audit.containers.root.GroupManagementLogs',
      defaultMessage: '组管理日志',
    }),

    key: 'group',
  },

  {
    value: intl.get({
      id: 'code-assets.audit.containers.root.EnterpriseManagementLogs',
      defaultMessage: '企业管理日志',
    }),

    key: 'organization',
  },
];

const visibility_levels = {
  0: intl.get({ id: 'code-assets.audit.containers.root.Private', defaultMessage: '私有' }),
  10: intl.get({
    id: 'code-assets.audit.containers.root.EnterprisePublic',
    defaultMessage: '企业内公开',
  }),
};

const roleInfo = {
  9999: intl.get({
    id: 'code-assets.audit.containers.root.EnterpriseMembersIncludingAdministrators',
    defaultMessage: '企业成员(含管理员)',
  }),

  5: intl.get({
    id: 'code-assets.audit.containers.root.ExternalMembersOfTheEnterprise',
    defaultMessage: '企业外部成员',
  }),
};

const cloneWay = {
  'ssh-clone': 'SSH Clone',
  'http-clone': 'HTTPS Clone',
  download: intl.get({
    id: 'code-assets.audit.containers.root.DownloadZipTar',
    defaultMessage: '下载ZIP/TAR',
  }),
};

// let timer = null;
// let timerSetout = null;

class Root extends Component {
  static propTypes = {
    tabKey: PropTypes.string,
    pageSize: PropTypes.number,
    currentPage: PropTypes.number,
    isLoadingTable: PropTypes.string,
    auditLogData: PropTypes.arrayOf(PropTypes.object),
    getAuditData: PropTypes.func,
    setTabKey: PropTypes.func,
    total: PropTypes.number,
  };

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.audit.containers.root.AuditLogsCloudEffectCodeup',
      defaultMessage: '审计日志 · 云效 Codeup',
    });

    this.props.getAuditData(1);

    enterPage('Organization-Settings-Audit', {
      sendPerf: false,
    });
  }

  componentWillUnmount() {
    this.props.resetData();
  }

  onPageNoChange = (page) => {
    this.props.getAuditData(page);
  };

  onPageSizeChange = (pageSize) => {
    this.props.getAuditData(1, pageSize);
  };

  onTabChange = (value) => {
    // 切换tab需清除所有筛选器中的数据（数据源不同）
    this.props.resetData();
    this.props.setTabKey(value);
    // if (!timer) {
    //   this.props.resetData();
    //   this.props.setTabKey(value);
    //   timer = new Date().getTime();
    // } else {
    //   const now = new Date().getTime();
    //   const val = now - timer;
    //   if (val > 500) {
    //     this.props.resetData();
    //     this.props.setTabKey(value);
    //     timer = new Date().getTime();
    //     timerSetout = null;
    //   } else {
    //     if (timerSetout) {
    //       clearTimeout(timerSetout);
    //     }
    //     timerSetout = setTimeout(() => {
    //       timer = new Date().getTime();
    //       this.props.resetData();
    //       this.props.setTabKey(value);
    //     }, 500 - val);
    //   }
    // }
  };

  onDownloadClick = () => {
    const { paramsData, tabKey } = this.props;
    const {
      tb_user_ids,
      type,
      project_id,
      start_time,
      end_time,
      entity_id,
      entity_type,
      audit_filter_type,
    } = paramsData;
    const searchData = Qs.stringify({
      tb_user_ids: tb_user_ids.map((item) => item._userId).join(','),
      type,
      project_id: project_id.join(','),
      start_time,
      end_time,
      entity_id: entity_id.map((item) => item._userId).join(','),
      entity_type,
      include_sub_group: tabKey === 'group',
      audit_filter_type,
    });

    navigateOpen(
      `/api/v4/organization/${window.FORCE.organization.id}/audit_log/download?${searchData}`,
    );
  };

  renderOperator = (value, index, record) => {
    return (
      <span className="one-line-ellipsis">
        <Title trigger={<span>{record.operator.name || record.operator.username}</span>}>
          <div>{record.operator.name || record.operator.username}</div>
        </Title>
      </span>
    );
  };

  renderTime = (value) => {
    return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
  };

  renderAction = (value, index, record) => {
    const { tabKey } = this.props;
    const member =
      record.entity_type === 'USER'
        ? record.entity_info.name || record.entity_info.username
        : '-------';
    switch (value) {
      case 'NEW_REPO':
        return intl.get({
          id: 'code-assets.audit.containers.root.NewCodeLibrary',
          defaultMessage: '新建了代码库',
        });

      case 'IMPORT_REPO':
        return intl.get({
          id: 'code-assets.audit.containers.root.ImportedCodeLibrary',
          defaultMessage: '导入了代码库',
        });

      case 'DEL_REPO': {
        const reason = record.detail !== undefined ? record.detail : '-------';
        return (
          <Title
            trigger={
              <span>
                {intl.get(
                  {
                    id: 'code-assets.audit.containers.root.TheCodeLibraryWasDeleted',
                    defaultMessage: '删除了代码库，原因: {reason}',
                  },

                  { reason },
                )}
              </span>
            }
          >
            <div>
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.TheCodeLibraryWasDeleted',
                  defaultMessage: '删除了代码库，原因: {reason}',
                },

                { reason },
              )}
            </div>
          </Title>
        );
      }
      case 'TRANSFER_REPO':
      case 'TRANSFER_GROUP': {
        return (
          <Title
            trigger={
              <span>
                {tabKey === 'group'
                  ? intl.get({
                    id: 'code-assets.audit.containers.root.TransferredTheCodeGroup',
                    defaultMessage: '转移了代码组',
                  })
                  : intl.get({
                    id: 'code-assets.audit.containers.root.TransferredTheCodeLibrary',
                    defaultMessage: '转移了代码库',
                  })}
              </span>
            }
          >
            <div>
              {tabKey === 'group'
                ? intl.get({
                  id: 'code-assets.audit.containers.root.TransferredTheCodeGroup',
                  defaultMessage: '转移了代码组',
                })
                : intl.get({
                  id: 'code-assets.audit.containers.root.TransferredTheCodeLibrary',
                  defaultMessage: '转移了代码库',
                })}
            </div>
          </Title>
        );
      }
      case 'RESTORE_REPO':
      case 'RESTORE_GROUP': {
        return (
          <Title
            trigger={
              <span>
                {tabKey === 'group'
                  ? intl.get({
                    id: 'code-assets.audit.containers.root.RestoredCodeGroups',
                    defaultMessage: '恢复了代码组',
                  })
                  : intl.get({
                    id: 'code-assets.audit.containers.root.RestoredTheCodeLibrary',
                    defaultMessage: '恢复了代码库',
                  })}
              </span>
            }
          >
            <div>
              {tabKey === 'group'
                ? intl.get({
                  id: 'code-assets.audit.containers.root.RestoredCodeGroups',
                  defaultMessage: '恢复了代码组',
                })
                : intl.get({
                  id: 'code-assets.audit.containers.root.RestoredTheCodeLibrary',
                  defaultMessage: '恢复了代码库',
                })}
            </div>
          </Title>
        );
      }
      case 'MOD_VISIBILITY':
      case 'MOD_GROUP_VISIBILITY': {
        const VSdetail = JSON.parse(record.detail);
        return (
          <Title
            trigger={
              <span>
                {intl.get(
                  {
                    id: 'code-assets.audit.containers.root.AdjustThePublicityToVisibilitylevelsvsdetail',
                    defaultMessage: '调整公开性为{visibilityLevelsVSdetail}',
                  },

                  { visibilityLevelsVSdetail: visibility_levels[VSdetail.current_visibility] },
                )}
              </span>
            }
          >
            <div>
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.AdjustThePublicityToVisibilitylevelsvsdetail',
                  defaultMessage: '调整公开性为{visibilityLevelsVSdetail}',
                },

                { visibilityLevelsVSdetail: visibility_levels[VSdetail.current_visibility] },
              )}
            </div>
          </Title>
        );
      }
      case 'MOD_MEMBER':
      case 'MOD_GROUP_MEMBER': {
        let memberInfo;
        if (record.entity_type === 'USER') {
          const detail = JSON.parse(record.detail);
          const memberType =
            tabKey === 'group'
              ? intl.get({
                id: 'code-assets.audit.containers.root.GroupMembers',
                defaultMessage: '组成员',
              })
              : intl.get({
                id: 'code-assets.audit.containers.root.DatabaseMember',
                defaultMessage: '库成员',
              });

          const username = record.entity_info.name || record.entity_info.username;
          if (detail.previous_access === 'NO_ACCESS' && detail.current_access !== 'NO_ACCESS') {
            memberInfo = intl.get(
              {
                id: 'code-assets.audit.containers.root.AddedTheMembertypeUsernamePermission',
                defaultMessage: '新增了{memberType}[{username}]的权限为{ENUMRoleDetail}',
              },

              {
                memberType,
                username,
                ENUMRoleDetail: ENUM.role[detail.current_access],
              },
            );
          } else if (
            detail.current_access === 'NO_ACCESS' &&
            detail.previous_access !== 'NO_ACCESS'
          ) {
            memberInfo = intl.get(
              {
                id: 'code-assets.audit.containers.root.DeletedMembertypeUsername',
                defaultMessage: '删除了{memberType}[{username}]',
              },

              { memberType, username },
            );
          } else if (
            detail.current_access !== 'NO_ACCESS' &&
            detail.previous_access !== 'NO_ACCESS'
          ) {
            memberInfo = intl.get(
              {
                id: 'code-assets.audit.containers.root.ChangedThePermissionOfMembertype',
                defaultMessage: '修改了{memberType}[{username}]的权限为{ENUMRoleDetail}',
              },

              {
                memberType,
                username,
                ENUMRoleDetail: ENUM.role[detail.current_access],
              },
            );
          } else {
            memberInfo = '-------';
          }
        } else {
          memberInfo = '-------';
        }
        return (
          <span className="one-line-ellipsis">
            <Title trigger={<span>{memberInfo}</span>}>
              <div>{memberInfo}</div>
            </Title>
          </span>
        );
      }
      case 'HTTP_CLONE':
        return 'HTTP CLONE';
      case 'SSH_CLONE':
        return 'SSH CLONE';
      case 'DOWNLOAD':
        return 'DOWNLOAD';
      case 'NEW_GROUP':
        return intl.get({
          id: 'code-assets.audit.containers.root.NewCodeGroup',
          defaultMessage: '新建了代码组',
        });

      case 'DEL_GROUP': {
        const reason = record.detail !== undefined ? record.detail : '-------';
        return (
          <Title
            trigger={
              <span>
                {intl.get(
                  {
                    id: 'code-assets.audit.containers.root.TheCodeGroupHasBeen',
                    defaultMessage: '删除了代码组，原因: {reason}',
                  },

                  { reason },
                )}
              </span>
            }
          >
            <div>
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.TheCodeGroupHasBeen',
                  defaultMessage: '删除了代码组，原因: {reason}',
                },

                { reason },
              )}
            </div>
          </Title>
        );
      }
      case 'ORG_ADD_ADMIN':
        return (
          <Title
            trigger={
              <span>
                {intl.get(
                  {
                    id: 'code-assets.audit.containers.root.AddMemberAsAnAdministrator',
                    defaultMessage: '添加普通成员[{member}]为管理员',
                  },

                  { member },
                )}
              </span>
            }
          >
            <div>
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.AddMemberAsAnAdministrator',
                  defaultMessage: '添加普通成员[{member}]为管理员',
                },

                { member },
              )}
            </div>
          </Title>
        );

      case 'ORG_ADD_OWNER':
        return (
          <Title
            trigger={
              <span>
                {intl.get(
                  {
                    id: 'code-assets.audit.containers.root.AddMemberAsTheOwner',
                    defaultMessage: '添加普通成员[{member}]为拥有者',
                  },

                  { member },
                )}
              </span>
            }
          >
            <div>
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.AddMemberAsTheOwner',
                  defaultMessage: '添加普通成员[{member}]为拥有者',
                },

                { member },
              )}
            </div>
          </Title>
        );

      case 'ORG_DEL_ADMIN':
        return (
          <Title
            trigger={
              <span>
                {intl.get(
                  {
                    id: 'code-assets.audit.containers.root.RemoveAdministratorMember',
                    defaultMessage: '移除管理员[{member}]',
                  },

                  { member },
                )}
              </span>
            }
          >
            <div>
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.RemoveAdministratorMember',
                  defaultMessage: '移除管理员[{member}]',
                },

                { member },
              )}
            </div>
          </Title>
        );

      case 'ORG_DEL_OWNER':
        return (
          <Title
            trigger={
              <span>
                {intl.get(
                  {
                    id: 'code-assets.audit.containers.root.RemoveOwnerMember',
                    defaultMessage: '移除拥有者[{member}]',
                  },

                  { member },
                )}
              </span>
            }
          >
            <div>
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.RemoveOwnerMember',
                  defaultMessage: '移除拥有者[{member}]',
                },

                { member },
              )}
            </div>
          </Title>
        );

      case 'ORG_MOD_RISK': {
        const detail = JSON.parse(record.detail);
        if (detail.sensitive_enable) {
          return intl.get({
            id: 'code-assets.audit.containers.root.EnableTheSensitiveBehaviorMonitoring',
            defaultMessage: '开启 [敏感行为监测] 服务',
          });
        } else {
          return intl.get({
            id: 'code-assets.audit.containers.root.DisableTheSensitiveBehaviorMonitoring',
            defaultMessage: '关闭 [敏感行为监测] 服务',
          });
        }
      }
      case 'ORG_MOD_IPLIST': {
        const ipListDetail = JSON.parse(record.detail);
        let ipListOperation;
        if (ipListDetail.ip_whitelist_enabled) {
          ipListOperation = intl.get(
            {
              id: 'code-assets.audit.containers.root.SetIpWhitelistAccessibleIp',
              defaultMessage: '设置 IP 白名单：可访问 IP [{ipListDetailIpWhitelist}]',
            },

            { ipListDetailIpWhitelist: ipListDetail.ip_whitelist },
          );
        } else {
          ipListOperation = intl.get({
            id: 'code-assets.audit.containers.root.DisableIpAddressWhitelist',
            defaultMessage: '关闭 IP 白名单',
          });
        }
        return (
          <Title trigger={<span>{ipListOperation}</span>}>
            <div>{ipListOperation}</div>
          </Title>
        );
      }
      case 'ORG_ENABLE_CLD':
      case 'REPO_ENABLE_CLD': {
        const detail = JSON.parse(record.detail);
        const detail_role_list = JSON.parse(detail.roleList) || [];
        const detail_method_list = JSON.parse(detail.methodList) || [];
        const role_list = [];
        const method_list = [];

        detail_role_list.forEach((item) => {
          if (item.allowed) {
            role_list.push(roleInfo[item.role_code]);
          }
        });
        detail_method_list.forEach((item) => {
          if (item.allowed) {
            method_list.push(cloneWay[item.permission_code]);
          }
        });
        const roleList = role_list.join('、');
        const methodList = method_list.join('、');
        const str = intl.get(
          {
            id: 'code-assets.audit.containers.root.EnableCloneDownloadToAllow',
            defaultMessage: '开启克隆下载设置，允许{roleList}{methodList}',
          },

          { roleList, methodList },
        );

        return (
          <Title trigger={<span>{str}</span>}>
            <div>{str}</div>
          </Title>
        );
      }
      case 'ORG_MOD_CLD':
      case 'REPO_MOD_CLD': {
        const detail = JSON.parse(record.detail);
        const detail_role_list = JSON.parse(detail.roleList) || [];
        const detail_method_list = JSON.parse(detail.methodList) || [];
        const role_list = [];
        const method_list = [];

        detail_role_list.forEach((item) => {
          if (item.allowed) {
            role_list.push(roleInfo[item.role_code]);
          }
        });
        detail_method_list.forEach((item) => {
          if (item.allowed) {
            method_list.push(cloneWay[item.permission_code]);
          }
        });
        const roleList = role_list.join('、');
        const methodList = method_list.join('、');
        const str = intl.get(
          {
            id: 'code-assets.audit.containers.root.ModifyTheCloneDownloadSettings',
            defaultMessage: '修改克隆下载设置，允许{roleList}{methodList}',
          },

          { roleList, methodList },
        );

        return (
          <Title trigger={<span>{str}</span>}>
            <div>{str}</div>
          </Title>
        );
      }
      case 'ORG_DISABLE_CLD':
      case 'REPO_DISABLE_CLD':
        return intl.get({
          id: 'code-assets.audit.containers.root.DisableCloneDownloadSettings',
          defaultMessage: '关闭克隆下载设置',
        });

      case 'ORG_BS_MOD_AUTH': {
        const detail = JSON.parse(record.detail);
        const str = detail.isRemove
          ? intl.get({
            id: 'code-assets.audit.containers.root.ConfigureBackupSpaceRevokeOss',
            defaultMessage: '设置备份空间：解除OSS服务授权',
          })
          : intl.get({
            id: 'code-assets.audit.containers.root.ConfigureBackupSpaceAuthorizeOss',
            defaultMessage: '设置备份空间：授权OSS服务',
          });

        return (
          <Title trigger={<span>{str}</span>}>
            <div>{str}</div>
          </Title>
        );
      }
      case 'ORG_BS_SET': {
        let str = '';
        try {
          const detail = JSON.parse(record.detail);
          const spaceInfo = JSON.parse(detail.backupSpace);
          const { spaceName } = spaceInfo;
          let locationName = '';
          ENUM.regions.forEach((r) => {
            if (r.value === spaceInfo.spaceLocation) {
              locationName = r.label ? r.label.replace('（', '(').replace('）', ')') : '';
            }
          });
          str = intl.get(
            {
              id: 'code-assets.audit.containers.root.SetBackupSpaceSetBucket',
              defaultMessage: '设置备份空间：设置 Bucket [{locationName},{spaceName}]',
            },

            { locationName, spaceName },
          );
        } catch (e) {
          str = '';
        }
        return (
          <Title trigger={<span>{str}</span>}>
            <div>{str}</div>
          </Title>
        );
      }
      case 'ORG_BS_MOD_SETTINGS': {
        let str = '';
        try {
          const detail = JSON.parse(record.detail);
          const spaceInfo = JSON.parse(detail.backupSpace);
          str = spaceInfo.isOpenAutoBackUp
            ? intl.get({
              id: 'code-assets.audit.containers.root.EnableScheduledBackup',
              defaultMessage: '开启定时备份',
            })
            : intl.get({
              id: 'code-assets.audit.containers.root.DisableScheduledBackup',
              defaultMessage: '关闭定时备份',
            });
        } catch (e) {
          str = '';
        }
        return str;
      }
      case 'ORG_BACK_UP_MANUAL': {
        return intl.get({
          id: 'code-assets.audit.containers.root.PerformManualBackup',
          defaultMessage: '执行手动备份',
        });
      }
      case 'ORG_CRYPTO_MOD_AUTH': {
        const detail = JSON.parse(record.detail);
        const str = detail.isRemove
          ? intl.get({
            id: 'code-assets.audit.containers.root.ConfigureRepositoryEncryptionRevokeKms',
            defaultMessage: '设置仓库加密：解除KMS服务授权',
          })
          : intl.get({
            id: 'code-assets.audit.containers.root.ConfigureRepositoryEncryptionAuthorizeKms',
            defaultMessage: '设置仓库加密：授权KMS服务',
          });

        return (
          <Title trigger={<span>{str}</span>}>
            <div>{str}</div>
          </Title>
        );
      }
      case 'ORG_CRYPTO_MOD_SETTINGS': {
        let str = '';
        try {
          const detail = JSON.parse(record.detail);
          const settings = JSON.parse(detail.settings);
          str += intl.get({
            id: 'code-assets.audit.containers.root.ConfigureRepositoryEncryption',
            defaultMessage: '设置仓库加密：',
          });

          str +=
            settings.crypto_level === cryptoLevelMap[1]
              ? intl.get({
                id: 'code-assets.audit.containers.root.ByDefaultEncryptionIsEnabled',
                defaultMessage: '新建仓库默认开启加密、',
              })
              : intl.get({
                id: 'code-assets.audit.containers.root.ByDefaultEncryptionIsDisabled',
                defaultMessage: '新建仓库默认不开启加密、',
              });

          str += settings.project_settings_enabled
            ? intl.get({
              id: 'code-assets.audit.containers.root.AllowsTheRepositoryAdministratorTo',
              defaultMessage: '允许仓库管理员修改加密设置',
            })
            : intl.get({
              id: 'code-assets.audit.containers.root.TheRepositoryAdministratorCannotModify',
              defaultMessage: '不允许仓库管理员修改加密设置',
            });
        } catch (e) {
          str = '';
        }
        return (
          <Title trigger={<span>{str}</span>}>
            <div>{str}</div>
          </Title>
        );
      }
      case 'MOD_ORG_REPO_SETTINGS': {
        return '更新代码库设置';
      }
      case 'MOD_ORG_GROUP_SETTINGS': {
        return '更新代码组设置';
      }
      default:
        return '';
    }
  };

  getIpText = (value) => {
    return (
      <span>
        <span>
          {value.ip_address || '-------'}{' '}
          {value.ip_location ? (
            <span
              title={intl.get(
                {
                  id: 'code-assets.audit.containers.root.LocationValueiplocation',
                  defaultMessage: '地点：{valueIpLocation}',
                },

                { valueIpLocation: value.ip_location },
              )}
            >
              {intl.get(
                {
                  id: 'code-assets.audit.containers.root.LocationValueiplocation',
                  defaultMessage: '地点：{valueIpLocation}',
                },

                { valueIpLocation: value.ip_location },
              )}
            </span>
          ) : (
            ''
          )}
        </span>
      </span>
    );
  };

  renderIp = (value) => {
    return (
      <Title
        trigger={this.getIpText(value)}
      >
        {this.getIpText(value)}
      </Title>
    );
  };

  renderMember = (value, index, record) => {
    if (record.entity_type === 'USER') {
      return (
        <Title trigger={<span>{record.entity_info.name || record.entity_info.username}</span>}>
          <div>{record.entity_info.name || record.entity_info.username}</div>
        </Title>
      );
    } else {
      return '-------';
    }
  };

  renderProject = (value) => {
    return (
      <Title trigger={<span>{value.path_with_namespace}</span>}>{value.path_with_namespace}</Title>
    );
  };

  renderAuditTable = (key) => {
    const { auditLogData, isLoadingTable, currentPage, total, tabKey } = this.props;
    return (
      <div>
        <div>
          {!isLoadingTable ? <Perf page="Organization-Settings-Audit" /> : null}
          <YunxiaoTable
            hasBorder
            dataSource={
              auditLogData && auditLogData[tabKey] && auditLogData[tabKey].length > 0
                ? auditLogData[tabKey]
                : []
            }
            loading={isLoadingTable}
            className="audit-log-table"
          >
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.audit.containers.root.Operator',
                defaultMessage: '操作人',
              })}
              // className="audit-log-operator-col"
              dataIndex="operator"
              cell={this.renderOperator}
              width={180}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.audit.containers.root.Date',
                defaultMessage: '日期',
              })}
              dataIndex="gmt_create"
              width={190}
              // style={{ width: 190 }}
              cell={this.renderTime}
            />

            <YunxiaoTable.Column
              width={240}
              title={intl.get({
                id: 'code-assets.audit.containers.root.Operation',
                defaultMessage: '操作',
              })}
              dataIndex="action_type"
              // className="audit-log-action-col"
              cell={this.renderAction}
            />

            {key !== 'organization' ? (
              <YunxiaoTable.Column
                width={220}
                title={
                  key === 'group'
                    ? intl.get({
                      id: 'code-assets.audit.containers.root.CodeGroup',
                      defaultMessage: '代码组',
                    })
                    : intl.get({
                      id: 'code-assets.audit.containers.root.CodeBase',
                      defaultMessage: '代码库',
                    })
                }
                dataIndex="project"
                // className="audit-log-project-col"
                cell={this.renderProject}
              />
            ) : null}

            <YunxiaoTable.Column
              title="IP"
              dataIndex="ip"
              width={280}
              // style={{ width: 200 }}
              cell={this.renderIp}
            />

            {/* <YunxiaoTable.Column title="IP" dataIndex="ip.ip_address" style={{ width: 144 }} /> */}
          </YunxiaoTable>

          <Pagination
            onChange={this.onPageNoChange}
            current={currentPage}
            total={total}
            pageSize={this.props.pageSize}
            onPageSizeChange={this.onPageSizeChange}
            leftWidth={Math.ceil(total / 10) === currentPage ? 360 : 0}
            footerProps={{
              left: Math.ceil(total / 10) === currentPage && (
                <div className="audit-table-help">支持查看最近 1 个月的操作日志，如需查看更多历史请提交
                  <a href={docs('log-limit')} target="_blank" rel="noreferrer">
                    {intl.get({
                      id: 'code-assets.audit.containers.root.TicketApplication',
                      defaultMessage: '工单申请',
                    })}
                  </a>
                </div>
              ),
              noBorderTop: true,
            }}
          />
        </div>
      </div>
    );
  };

  openSlsAuthPage = () => {
    // const { isAuthorizing } = this.props;
    // if (isAuthorizing) {
    //   return;
    // }
    // track({
    //   action: 'authorized oss',
    //   page: 'Organization-Settings-backup',
    //   type: '',
    //   control: '',
    // });
    const { authRedirectUrl } = this.props.slsInfo || {};
    if (!authRedirectUrl) return;
    const openedWindow = navigateOpen(authRedirectUrl);
    const windowChecker = setInterval(() => {
      if (openedWindow.location.pathname === '/oauth/aliyun/success') {
        window.clearInterval(windowChecker);
        this.props.slsAuthorize('AliyunRDCCodeAuditRole');
        if (!openedWindow.closed) {
          openedWindow.close();
        }
      }
    }, 500);
  };

  removeSlsAuth = () => {
    const { authorization_id } = this.props.slsInfo || {};
    if (!authorization_id) return;
    this.props.removeAuth(authorization_id);
  };

  render() {
    return (
      <>
        <Header
          title={intl.get({
            id: 'code-assets.audit.containers.root.AuditLogs',
            defaultMessage: '审计日志',
          })}
        />

        <Content>
          <Tab
            className="sls-root-tab"
            navClassName="sls-root-nav"
            onChange={this.onMainTabChange}
            size="small"
            animation={false}
          >
            <Tab.Item
              title={intl.get({
                id: 'code-assets.audit.containers.root.LogOverview',
                defaultMessage: '日志概览',
              })}
              key="overview"
            >
              <Tab
                // className="audit-log-tab"
                onChange={this.onTabChange}
                shape="capsule"
                animation={false}
                extra={
                  <div style={{ position: 'relative' }}>
                    <FilterForm {...this.props} />
                    <Balloon.Tooltip
                      trigger={
                        <Button
                          type="primary"
                          text
                          onClick={this.onDownloadClick}
                          style={{ marginLeft: 8 }}
                        >
                          <YunxiaoIcon type="export-module-line" />
                          {intl.get({
                            id: 'code-assets.audit.containers.root.Export',
                            defaultMessage: '导出',
                          })}
                        </Button>
                      }
                      align="tr"
                    >
                      {intl.get({
                        id: 'code-assets.audit.containers.root.AMaximumExportBarIf',
                        defaultMessage: '一次最多导出 10000 条，若超过，可通过筛选分次导出',
                      })}
                    </Balloon.Tooltip>
                  </div>
                }
              >
                {tabDataSource.map((item) => (
                  <Tab.Item title={item.value} key={item.key}>
                    {this.renderAuditTable(item.key)}
                  </Tab.Item>
                ))}
              </Tab>
            </Tab.Item>
            {getFeature('page_enable.org.setting.audit') &&
              <Tab.Item
                title={intl.get({
                  id: 'code-assets.audit.containers.root.LogAnalysis',
                  defaultMessage: '日志分析',
                })}
                key="analysis"
              >
                <SlsService {...this.props} />
              </Tab.Item>}
          </Tab>
        </Content>
      </>
    );
  }
}

export default connect(
  (state) => state.organization.settings.audit,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
